#!/bin/bash

# PCF API Server Docker Management Script

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
IMAGE_NAME="pcf-api-server"
CONTAINER_NAME="pcf-api-server-demo"
PORT="1026"

# Function to print colored output
print_status() {
    local status=$1
    local message=$2
    case $status in
        "SUCCESS")
            echo -e "${GREEN}✓${NC} $message"
            ;;
        "ERROR")
            echo -e "${RED}✗${NC} $message"
            ;;
        "INFO")
            echo -e "${BLUE}ℹ${NC} $message"
            ;;
        "WARNING")
            echo -e "${YELLOW}⚠${NC} $message"
            ;;
    esac
}

# Function to build the Docker image
build_image() {
    print_status "INFO" "Building PCF API Server Docker image..."
    docker build -t $IMAGE_NAME .
    print_status "SUCCESS" "Docker image built successfully"
}

# Function to run the container
run_container() {
    print_status "INFO" "Starting PCF API Server container..."
    
    # Check if container already exists
    if docker ps -a --format 'table {{.Names}}' | grep -q "^$CONTAINER_NAME$"; then
        print_status "WARNING" "Container $CONTAINER_NAME already exists"
        read -p "Do you want to remove the existing container? (y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            docker rm -f $CONTAINER_NAME
            print_status "SUCCESS" "Existing container removed"
        else
            print_status "INFO" "Using existing container"
        fi
    fi
    
    # Run the container
    docker run -d \
        --name $CONTAINER_NAME \
        -p $PORT:$PORT \
        -e PORT=$PORT \
        -e FLASK_ENV=production \
        -v "$(pwd)/data:/app/data" \
        --restart unless-stopped \
        $IMAGE_NAME
    
    print_status "SUCCESS" "PCF API Server container started"
    print_status "INFO" "Server is running at http://localhost:$PORT"
}

# Function to stop the container
stop_container() {
    print_status "INFO" "Stopping PCF API Server container..."
    if docker ps --format 'table {{.Names}}' | grep -q "^$CONTAINER_NAME$"; then
        docker stop $CONTAINER_NAME
        print_status "SUCCESS" "Container stopped"
    else
        print_status "WARNING" "Container is not running"
    fi
}

# Function to remove the container
remove_container() {
    print_status "INFO" "Removing PCF API Server container..."
    if docker ps -a --format 'table {{.Names}}' | grep -q "^$CONTAINER_NAME$"; then
        docker rm -f $CONTAINER_NAME
        print_status "SUCCESS" "Container removed"
    else
        print_status "WARNING" "Container does not exist"
    fi
}

# Function to show container logs
show_logs() {
    print_status "INFO" "Showing container logs..."
    if docker ps --format 'table {{.Names}}' | grep -q "^$CONTAINER_NAME$"; then
        docker logs -f $CONTAINER_NAME
    else
        print_status "ERROR" "Container is not running"
    fi
}

# Function to test the API
test_api() {
    print_status "INFO" "Testing PCF API Server..."
    
    # Wait a moment for the server to start
    sleep 3
    
    # Test health endpoint
    if curl -s http://localhost:$PORT/health > /dev/null; then
        print_status "SUCCESS" "Health check passed"
    else
        print_status "ERROR" "Health check failed"
        return 1
    fi
    
    # Test PCF subscription endpoint
    if curl -s "http://localhost:$PORT/service/user/PcfSubscription?number=8613764010195" > /dev/null; then
        print_status "SUCCESS" "PCF subscription API test passed"
    else
        print_status "ERROR" "PCF subscription API test failed"
        return 1
    fi
    
    print_status "SUCCESS" "All API tests passed!"
}

# Function to show container status
show_status() {
    print_status "INFO" "Container status:"
    docker ps -a --filter "name=$CONTAINER_NAME" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
}

# Function to show usage
show_usage() {
    echo "PCF API Server Docker Management Script"
    echo "======================================"
    echo ""
    echo "Usage: $0 [COMMAND]"
    echo ""
    echo "Commands:"
    echo "  build     Build the Docker image"
    echo "  run       Build and run the container"
    echo "  start     Start the container (if it exists)"
    echo "  stop      Stop the container"
    echo "  restart   Restart the container"
    echo "  remove    Remove the container"
    echo "  logs      Show container logs"
    echo "  test      Test the API endpoints"
    echo "  status    Show container status"
    echo "  help      Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 run     # Build and start the server"
    echo "  $0 test    # Test the API endpoints"
    echo "  $0 logs    # View server logs"
}

# Main script logic
case "${1:-help}" in
    "build")
        build_image
        ;;
    "run")
        build_image
        run_container
        test_api
        ;;
    "start")
        if docker ps -a --format 'table {{.Names}}' | grep -q "^$CONTAINER_NAME$"; then
            docker start $CONTAINER_NAME
            print_status "SUCCESS" "Container started"
        else
            print_status "ERROR" "Container does not exist. Run '$0 run' first."
        fi
        ;;
    "stop")
        stop_container
        ;;
    "restart")
        stop_container
        sleep 2
        if docker ps -a --format 'table {{.Names}}' | grep -q "^$CONTAINER_NAME$"; then
            docker start $CONTAINER_NAME
            print_status "SUCCESS" "Container restarted"
        else
            print_status "ERROR" "Container does not exist. Run '$0 run' first."
        fi
        ;;
    "remove")
        remove_container
        ;;
    "logs")
        show_logs
        ;;
    "test")
        test_api
        ;;
    "status")
        show_status
        ;;
    "help"|*)
        show_usage
        ;;
esac 